/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  OwnerListActivity.java   
 * @Package com.jiyi.activity.escape   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-9-22 下午4:19:35   
 * @version V1.0     
 */
package com.jiyi.activity.escape;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.android.volley.VolleyError;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.adapter.DividerItemDecoration;
import com.jiyi.adapter.recyclerview.CommonAdapter;
import com.jiyi.adapter.recyclerview.base.ViewHolder;
import com.jiyi.adapter.recyclerview.wrapper.EmptyWrapper;
import com.jiyi.bean.owner.OwnerBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.inteface.WebApi;
import com.jiyi.widget.ClearEditText;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: OwnerListActivity
 * @Description:TODO(业主列表)
 * @author: HYM
 * @date: 2017-9-22 下午4:19:35
 * 
 */
public class OwnerListWithMapActivity extends ActivityBase implements
		OnRefreshListener {

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.ivSearch)
	ImageView ivSearch;

	@BindView(R.id.etSearch)
	ClearEditText etSearch;
	@BindView(R.id.map)
	TextureMapView map;
	@BindView(R.id.refreshLayout)
	SwipeRefreshLayout refreshLayout;
	@BindView(R.id.mainList)
	RecyclerView mainList;

	private List<OwnerBean> dataList = new ArrayList<OwnerBean>();
	EmptyWrapper adapter;
	private BaiduMap mBaiduMap;
	// 加载进度条
	Dialog dialog;
	// 默认1 地图 2 列表
	int type = 1;
	LayoutInflater inflater;
	View view;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_owner_list_with_map);
		ButterKnife.bind(this);
		init();
	}

	@Override
	protected void onResume() {
		super.onResume();
		map.onResume();
	}

	@Override
	protected void onPause() {
		map.onPause();
		super.onPause();
	}

	private void init() {
		inflater = LayoutInflater.from(this);
		initViewState();
		initMap();
		setTop();
		setAdapter();
		getData(null);
	}

	/**
	 * @author: HYM
	 * @Title: initMap
	 * @Description: TODO(初始化地图相关) void
	 * @date: 2017-9-25
	 */
	private void initMap() {
		mBaiduMap = map.getMap();
		// 获取地图的标注对象
		view = inflater.inflate(R.layout.mark_info, map, false);
		// 设置标注的点击监听事件
		mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {

			@Override
			public boolean onMarkerClick(Marker marker) {

				// 获得marker中的数据
				String company_id = (String) marker.getExtraInfo().get(
						"company_id");

				Intent intent = new Intent(view.getContext(),
						BuildActivity.class);
				intent.putExtra("company_id", company_id);
				startActivity(intent);
				return false;
			}
		});
	}

	private void initViewState() {
		// 设置输入法的搜索事件
		etSearch.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH
						|| actionId == EditorInfo.IME_ACTION_DONE) {
					InputMethodManager imm = (InputMethodManager) v
							.getContext().getSystemService(
									Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

					Log.e("onEditorAction  ", "   done ");
					getData(etSearch.getText().toString());
					return true;
				}
				return false;
			}
		});
	}

	private void setTop() {
		tvTitle.setText("逃生定位");
	}

	@OnClick({ R.id.tvBack, R.id.ivSearch })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tvBack:
			finish();
			break;
		case R.id.ivSearch:
			if (type == 1) {
				setRight(R.mipmap.icon_map);
				refreshLayout.setVisibility(View.VISIBLE);
				map.setVisibility(View.GONE);
				type = 2;
			} else {
				setRight(R.mipmap.icon_list);
				refreshLayout.setVisibility(View.GONE);
				map.setVisibility(View.VISIBLE);
				type = 1;
			}
			break;
		default:
			break;
		}
	}

	void setRight(int ResId) {
		ivSearch.setImageResource(ResId);
	}

	@Override
	public void onRefresh() {
		getData(null);
	}

	private void getData(final String keyword) {

		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		if (!TextUtils.isEmpty(keyword)) {
			params.put("keyword", keyword);
		}
		params.put("type", "2");

		dialog = showDialog(dialog);
		VolleyRequest.StringRequestPost(this, WebApi.MAINTENANCE_OWNER_LIST,
				"", params, new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<OwnerBean> temp = new Gson().fromJson(
										data, new TypeToken<List<OwnerBean>>() {
										}.getType());
								dataList.clear();
								dataList.addAll(temp);
								adapter.notifyDataSetChanged();

								if (type == 1 && !TextUtils.isEmpty(keyword)) {
									// 如果在地图模式下搜索没有数据的时候给出提示
									if (temp == null || temp.size() <= 0) {
										ToastUtil.getInstances().showMsg(
												"没有查找到该公司的信息");
									}
								}

								boolean firstLocation = false;
								for (int i = 0; i < temp.size(); i++) {
									OwnerBean tempbBean = temp.get(i);
									if (!TextUtils.isEmpty(tempbBean
											.getGeo_lat())
											&& !TextUtils.isEmpty(tempbBean
													.getGeo_lng())) {
										markInMap(tempbBean);
									}

									if (TextUtils.isEmpty(keyword)) {
										// 如果没有关键词 默认定位到万翔商务
										initDefaultLocation(
												AppConfig.escape_lat,
												AppConfig.escape_lgn);
									} else {
										// 有关键词定位到第一个关键词
										if (!firstLocation
												&& !TextUtils.isEmpty(tempbBean
														.getGeo_lat())
												&& !TextUtils.isEmpty(tempbBean
														.getGeo_lng())) {
											// 自动地位到第一条有地图数据上的业主
											initDefaultLocation(
													Double.parseDouble(tempbBean
															.getGeo_lat()),
													Double.parseDouble(tempbBean
															.getGeo_lng()));
											firstLocation = true;
										}
									}

								}

							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							hideDialog(dialog);
							refreshLayout.setRefreshing(false);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
						refreshLayout.setRefreshing(false);
					}
				});

	}

	private void setAdapter() {
		// 设置refreshLayout的监听
		refreshLayout.setColorSchemeColors(Color.RED, Color.YELLOW, Color.BLUE,
				Color.GREEN);
		refreshLayout.setOnRefreshListener(this);
		// 设置布局管理器
		mainList.setLayoutManager(new LinearLayoutManager(this));
		// 添加分割线
		mainList.addItemDecoration(new DividerItemDecoration(this,
				DividerItemDecoration.VERTICAL_LIST, null));
		// 初始化适配器
		CommonAdapter commonAdapter = new CommonAdapter<OwnerBean>(this,
				R.layout.item_owner, dataList) {
			@Override
			protected void convert(ViewHolder holder, final OwnerBean t,
					final int position) {
				holder.setText(R.id.tvOwnerName, t.getCompany_name());
				holder.setText(R.id.tvOwnerAddress, t.getCompany_address());
				holder.setOnClickListener(R.id.rlRoot, new OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(v.getContext(),
								BuildActivity.class);
						intent.putExtra("company_id", t.getCompany_id());
						startActivity(intent);
					}
				});
			}
		};

		adapter = new EmptyWrapper(commonAdapter);
		View emptyView = inflater.inflate(R.layout.empty_view_text_and_image,
				mainList, false);
		ImageView ivEmptyTip = (ImageView) emptyView
				.findViewById(R.id.ivEmptyTip);
		TextView tvEmptyTip = (TextView) emptyView
				.findViewById(R.id.tvEmptyTip);
		ivEmptyTip.setImageResource(R.mipmap.tip_empty_huodong);
		tvEmptyTip.setText(R.string.NO_DATA);
		adapter.setEmptyView(emptyView);

		// recycleview设置适配器
		mainList.setAdapter(adapter);
	}

	void markInMap(final OwnerBean ownerBean) {

		// 定义Maker坐标点
		LatLng point = new LatLng(Double.parseDouble(ownerBean.getGeo_lat()),
				Double.parseDouble(ownerBean.getGeo_lng()));
		// 设置图标的名称
		TextView tvTitle = (TextView) view.findViewById(R.id.tv_position);
		tvTitle.setText(ownerBean.getCompany_name());
		// 构建Marker图标
		BitmapDescriptor bitmap = BitmapDescriptorFactory.fromView(view);
		// 构建MarkerOption，用于在地图上添加Marker
		OverlayOptions option = new MarkerOptions().position(point)
				.icon(bitmap);
		// 在地图上添加Marker，并显示
		Marker marker = (Marker) mBaiduMap.addOverlay(option);
		Bundle bundle = new Bundle();
		bundle.putSerializable("company_id", ownerBean.getCompany_id());
		marker.setExtraInfo(bundle);
	}

	/**
	 * @author: HYM
	 * @Title: initDefaultLocation
	 * @Description: TODO(初始化地图的默认位置) void
	 * @date: 2017-9-25
	 */
	void initDefaultLocation(double lat, double lgn) {
		// 定位当前位置并做标记
		MyLocationData locData = new MyLocationData.Builder().accuracy(300F)
		// 此处设置开发者获取到的方向信息，顺时针0-360
				.direction(100).latitude(lat).longitude(lgn).build();
		mBaiduMap.setMyLocationData(locData);

		// 移动到定位位置
		LatLng ll = new LatLng(lat, lgn);
		MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
		mBaiduMap.setMapStatus(MapStatusUpdateFactory
				.newMapStatus(new MapStatus.Builder().zoom(16).build()));
		mBaiduMap.animateMapStatus(u);
	}
}
